package com.csust.travel.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.csust.travel.entity.*;
import com.csust.travel.mapper.CommentMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import javax.annotation.processing.Filer;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import com.fasterxml.jackson.databind.ObjectMapper;  // 使用这个import


@RestController
@CrossOrigin
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    private ResourceLoader resourceLoader;

    @PostMapping("/create")
    public ResBean createComment(HttpServletRequest request,
                                 @RequestPart(value = "imgFiles", required = false) MultipartFile[] imgFiles) {

        try {
            // 获取formData部分
            String formDataJson = request.getParameter("formData");
            System.out.println("Received formDataJson: " + formDataJson);

            if (formDataJson == null || formDataJson.trim().isEmpty()) {
                return new ResBean(false, "表单数据为空");
            }

            ObjectMapper mapper = new ObjectMapper();
            JsonNode formData = mapper.readTree(formDataJson);

            Comment comment = new Comment();
            comment.setReviewer(formData.get("reviewer").asInt());
            comment.setBook_name(formData.get("book_name").asText());
            comment.setBook_img(formData.get("book_img").asText());
            comment.setTransaction_date(formData.get("transaction_date").asText());
            comment.setRate(formData.get("rate").asInt());
            comment.setOrder_id(formData.get("order_id").asInt());
            comment.setContent(formData.get("content").asText());

            List<String> imgList = new ArrayList<>();
            if (imgFiles != null) {
                for (MultipartFile imgFile : imgFiles) {
                    if (imgFile != null && !imgFile.isEmpty()) {
                        ResBean uploadResult = upload(imgFile);
                        if (uploadResult.isFlag()) {
                            imgList.add((String) uploadResult.getData());
                        } else {
                            return new ResBean(false, "图片上传失败");
                        }
                    }
                }
            }

            comment.setImgList(imgList);
            commentMapper.saveItem(comment);
            Integer seller_id = commentMapper.getUser_id(comment.getOrder_id()) ;
            commentMapper.addComment(seller_id);
            return new ResBean(true, "评论成功", comment.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return new ResBean(false, "评论失败: " + e.getMessage());
        }
    }
    @PostMapping("/recreate")
    public ResBean RecreateComment(HttpServletRequest request,
                                 @RequestPart(value = "imgFiles", required = false) MultipartFile[] imgFiles) {
        try {
            // 获取formData部分
            String formDataJson = request.getParameter("formData");
            System.out.println("Received formDataJson: " + formDataJson);

            if (formDataJson == null || formDataJson.trim().isEmpty()) {
                return new ResBean(false, "表单数据为空");
            }

            ObjectMapper mapper = new ObjectMapper();
            JsonNode formData = mapper.readTree(formDataJson);

            Recomment recomment = new Recomment();
            recomment.setComment_id(formData.get("comment_id").asInt());
            recomment.setBook_name(formData.get("book_name").asText());
            recomment.setBook_img(formData.get("book_img").asText());
            recomment.setTransaction_date(formData.get("transaction_date").asText());
            recomment.setRate(formData.get("rate").asInt());
            recomment.setOrder_id(formData.get("order_id").asInt());
            recomment.setContent(formData.get("content").asText());

            List<String> imgList = new ArrayList<>();
            if (imgFiles != null) {
                for (MultipartFile imgFile : imgFiles) {
                    if (imgFile != null && !imgFile.isEmpty()) {
                        ResBean uploadResult = upload(imgFile);
                        if (uploadResult.isFlag()) {
                            imgList.add((String) uploadResult.getData());
                        } else {
                            return new ResBean(false, "图片上传失败");
                        }
                    }
                }
            }

            recomment.setImgList(imgList);
            commentMapper.saveReItem(recomment);
            return new ResBean(true, "评论成功", recomment.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return new ResBean(false, "评论失败: " + e.getMessage());
        }
    }
    @RequestMapping("/hasRecommented")
    public ResBean hasCommented(Integer num1) {
        commentMapper.setHasRecommented(num1);
        return new ResBean(true, "");
    }

    @RequestMapping("/getrecomment")
    public ResBean getRecomment(Integer id) {
        Recomment recomment =new Recomment();
        recomment = commentMapper.getRecomment(id);
        return new ResBean(true, "",recomment);
    }

    @PostMapping("/upload")
    public ResBean upload(MultipartFile imgFile) {
        try {
            // 获取原始文件名
            String originalFilename = imgFile.getOriginalFilename();

            // 获取文件扩展名
            String fileExtension = getFileExtension(originalFilename);

            // 生成新的文件名
            String newFileName = UUID.randomUUID().toString() + "." + fileExtension;
            String targetPath = "classpath:/static/upload/";
            Resource resource = resourceLoader.getResource(targetPath);

            // 直接获取upload目录的File对象
            File targetDir = resource.getFile();

            if (!targetDir.exists()) {
                targetDir.mkdirs(); // 创建目录
            }

            // 创建目标文件对象
            File f = new File(targetDir, newFileName);

            // 将文件从临时位置复制到目标位置
            imgFile.transferTo(f);

            return new ResBean(true, "上传成功666", newFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResBean(false, "上传失败666");
    }

    @RequestMapping("/all")
    public ResBean pageAll(@RequestBody pageDate pageData) {
        PageHelper.startPage(pageData.getCurrentPage(), pageData.getPageSize());
        List<Comment> Items;
        Items = commentMapper.findAllItem();
        PageInfo<Comment> commentPageInfo = new PageInfo<>(Items);
        return new ResBean(true, null, commentPageInfo);
    }


    @RequestMapping("/MyComment")
    public ResBean pageMyComment(@RequestBody pageDate pageData) {
        PageHelper.startPage(pageData.getCurrentPage(), pageData.getPageSize());
        List<Comment> Items;
        Items = commentMapper.findMyComment(pageData.getMyComment());
        PageInfo<Comment> commentPageInfo = new PageInfo<>(Items);
        return new ResBean(true, null, commentPageInfo);
    }

    @RequestMapping("/CommentMy")
    public ResBean pageCommentMy(@RequestBody pageDate pageData) {
        PageHelper.startPage(pageData.getCurrentPage(), pageData.getPageSize());
        List<Comment> Items;
        Items = commentMapper.findCommentMy(pageData.getMyComment());
        for (Comment comment : Items) {
           comment.setUser_id(commentMapper.getUser_id(comment.getOrder_id()));
        }
        PageInfo<Comment> commentPageInfo = new PageInfo<>(Items);
        return new ResBean(true, null, commentPageInfo);
    }


    @RequestMapping("/page")
    public ResBean page(@RequestBody pageDate pageData) {
        PageHelper.startPage(pageData.getCurrentPage(), pageData.getPageSize());
        List<Comment> Items;
        String queryString =pageData.getQueryString();
        Integer na = pageData.getRate();
        if ((isEmptyString1(queryString)) && (isEmptyString(na))) {
            Items = commentMapper.findAllItem();
        } else if (isEmptyString1(queryString) && !isEmptyString(na)) {
            Items = commentMapper.findBooksByNationality(na);
        } else if (!isEmptyString1(queryString) && isEmptyString(na)) {
            Items = commentMapper.findByQuery(queryString);
        } else {
            Items = commentMapper.findByFilters(queryString, na);
        }
        PageInfo<Comment> commentPageInfo = new PageInfo<>(Items);
        return new ResBean(true, null, commentPageInfo);
    }

    public boolean isEmptyString(Integer s) {
        return (s == null) ;
    }
    public boolean isEmptyString1(String s) {
        return (s == null) || s.trim().equals("");
    }
    @RequestMapping("/del")
    public ResBean delItem(Integer id) {
        try {
            commentMapper.delItem(id);
            return new ResBean(true, "删除成功666");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResBean(false, "删除失败");
    }



    // 获取文件扩展名的方法
    private String getFileExtension(String filename) {
        int dotIndex = filename.lastIndexOf('.');
        if (dotIndex == -1) {
            return ""; // 文件没有扩展名
        }
        return filename.substring(dotIndex + 1).toLowerCase(); // 返回扩展名
    }
}
